'''
Author: thinktanker thinktanker@163.com
Date: 2023-01-30 10:26:11
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2024-07-19 16:33:26
FilePath: \wxtest\swpng.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import requests
import time
import os
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO


def getswpng(ID_list: list, imgtype: int):
    """_summary_

    Args:
        ID_list (list): 工程id列表
        imgtype (int): 1 水位；2 趋势

    Returns:
        _type_: 合并后的图片bytes
    """
    img_list = []
    for _ID in ID_list:
        if imgtype == 1:
            url = 'http://www.jsswj.com.cn:88/jsswxxSSI/static/map1/0/3/{}.png?t={}/'
        elif imgtype == 2:
            url = 'http://www.jsswj.com.cn:88/jsswxxSSI/static/map/chart/0/{}.png?t={}'
        url = url.format(_ID[0], int(time.time() * 1000))
        resp = requests.get(url=url)
        print(url)
        if resp:
            if imgtype == 2:
                img_data = Image.open(BytesIO(resp.content))
                img_list.append(
                    settxtpng(
                        img_data,
                        f"{os.path.abspath(os.curdir)}{os.sep}data{os.sep}{_ID[0]}_{imgtype}.png",
                        _ID[1], imgtype))
            else:
                with open(
                        f"{os.path.abspath(os.curdir)}{os.sep}data{os.sep}{_ID[0]}_{imgtype}.png",
                        'wb') as f:
                    f.write(resp.content)
        # time.sleep(0.5)
    if img_list:
        return mergepng(
            imglist=img_list,
            savepath=
            f"{os.path.abspath(os.curdir)}{os.sep}data{os.sep}qushi.png")


def getqspng(gcname):
    """_summary_

    Returns:
        _type_: 合并后的图片bytes
    """
    # url = 'http://223.68.11.42:8211/qs'
    url = "https://pic.u96242.nyat.app:14861/qs?gcname=" + gcname
    qspng = requests.get(url=url).content
    # print(qspng)
    return qspng


def settxtpng(img: Image, imgpath: str, text: str, imgtype):
    """_summary_

    Args:
        img (Image): _description_
        imgpath (str): _description_
        text (str): _description_
        imgtype (_type_): _description_

    Returns:
        _type_: Image
    """

    # 打开图片
    # img = Image.open(imgpath)
    width, height = img.size
    # 获取图片的绘图对象
    draw = ImageDraw.Draw(img)

    # 设置字体，这里假设你已经有了一个.ttf字体文件
    font = ImageFont.truetype(
        f'{os.path.abspath(os.curdir)}{os.sep}data{os.sep}Yahei.ttf',
        size=20)  # 字体文件路径和字体大小
    # 定义文字内容和位置
    # text = "Hello, World!"
    text_position = (int(width / 2 - draw.textlength(text, font=font) / 2), 0
                     )  # 文字左上角的坐标

    # 在图片上绘制文字
    draw.text(text_position, text, font=font, fill=(0, 0, 0))

    # 保存修改后的图片
    img.save(imgpath)
    return img


def mergepng(imglist: list, savepath: str):
    img_width_list = []
    img_height_list = []
    for img in imglist:
        w, h = img.size
        img_width_list.append(w)
        img_height_list.append(h)
    width = max(img_width_list)
    height = sum(img_height_list)
    # 创建一个新的Image对象，尺寸为两幅图片相加的高度，宽度取较大的那幅图片
    new_img = Image.new('RGB', (width, height), (255, 255, 255))  # 白色背景

    # 将图片从上到下依次粘贴到新的Image对象上
    for i, img in enumerate(imglist):
        new_img.paste(img, (0, sum(img_height_list[:i])))

    # 保存组合后的图片
    img_byte_array = BytesIO()
    new_img.save(savepath, 'PNG')
    new_img.save(img_byte_array, 'PNG')
    return img_byte_array.getvalue()


if __name__ == '__main__':
    from myconfig import *
    # img1 = Image.open('./data/4e6ec458bb1240e9bfaf67a539fb5783_2.png')
    # img2 = Image.open('./data/ec4ccb4a8af049ceb1a6517506f14e6f_2.png')
    # img3 = Image.open('./data/9789b39bf27b4f338820f1fa6eef84e7_2.png')
    # img4 = Image.open('./data/746369696c4b4cf09d1a652aa845c94c_2.png')
    # img_list = [img1, img2, img3, img4]
    # mergepng(img_list, './data/combined_image.jpg')
    getswpng(ID_list=swid_list, imgtype=2)
